<template>
	<view class="wrap">
		<view class="innerItem">
			<!-- #ifdef APP-PLUS -->
				<view class="mineItem" @tap="settingHead">
					<view class="mineTit">头像</view> 
					<view class="hasFlex">
						<image class="samePar" :src="mainImg == '' ? '../../../static/images/defHead.png' : getUrl(mainImg)"></image>
						<!-- <view class="iconfont icon-gengduo"></view> -->
					</view>
				</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
				<view class="mineItemH5">
					<!-- <view class="cropperItem">
						<h5-cropper @getbase64Data="getbase64Data"></h5-cropper>
					</view> -->
					<view class="innerItemH5">
						<view class="mineTit">头像</view>
						<view class="hasFlex">
							<image class="samePar" :src="mainImg == '' ? '../../../static/images/defHead.png' : getUrl(mainImg)"></image>
							<!-- <view class="iconfont icon-gengduo"></view> -->
						</view>
					</view>
				</view>
			<!-- #endif -->
			<view class="mineItem">
				<view class="mineTit">姓名</view>
				<view class="hasFlex">
					<view class="currVersion">{{realName}}</view>
				</view>
			</view>
			<view class="mineItem">
				<view class="mineTit">身份角色</view>
				<view class="hasFlex">
					<view class="currVersion">{{roleName}}</view>
				</view>
			</view>
			<view class="mineItem" v-if="roleName == '学生'">
				<view class="mineTit">年级</view>
				<view class="hasFlex">
					<view class="currVersion">{{gradeNo}}级</view>
				</view>
			</view>
			<!-- #ifdef APP-PLUS -->
			<view class="mineItem" @tap="clearCache">
				<view class="mineTit">清除缓存</view>
				<view class="hasFlex">
					<view class="currVersion">{{fileSizeString}}</view>
					<view class="iconfont icon-gengduo"></view>
				</view>
			</view>
			<!-- <view class="mineItem" @tap="checkVersion">
				<view class="mineTit">版本更新</view>
				<view class="hasFlex">
					<view class="currVersion">当前版本{{currVersion}}</view>
					<view class="iconfont icon-gengduo"></view>
				</view>
			</view> -->
			<!-- #endif -->
		</view> 
		<button class="comBtn" @tap="logoOut">退出登录</button>
		<common-alert :showAlertFlag="showAlertFlag" :maskClosable="maskClosable" @closeAlertComponent="closeAlertComponent">
			<block v-if="currOpt == 'logOut'">
				<view class="alertContent">是否确认退出登录?</view>
				<view class="tui-alert-btn" :hover-stay-time="150">
					<view class="cancelBtn" @tap.stop="cancel">取消</view>
					<view class="sureBtn" @tap="sureLogout">确认</view> 
				</view>
			</block>
			<block v-else-if="currOpt == 'clearCache'">
				<view class="alertContent">是否确认清除缓存?</view>
				<view class="tui-alert-btn" :hover-stay-time="150">
					<view class="cancelBtn" @tap.stop="cancel">取消</view>
					<view class="sureBtn" @tap="sureClear">确认</view> 
				</view>
			</block>
		</common-alert>
	</view>
</template>
<script>
	var sourceType = '';
	// import { upSex } from '@/api/mine/index'
	// // #ifdef H5
	// import H5Cropper from "vue-cropper-h5"
	// //import { upUserHead } from '@/api/mine/index'
	// // #endif
	export default {
		// components: {
		// 	// #ifdef H5
		// 		H5Cropper 
		// 	// #endif
		// },
		data(){
			return{
				mainImg:'',
				showAlertFlag:false,
				maskClosable:true,
				fileSizeString:'',
				currOpt:'',//logOut clearCache
				sizeCache:0,
				realName:'',
				gradeNo:'',
				currVersion:''
			}
		},
		computed:{
			getUrl(){
				return function(url){
					if(url != undefined){
						if(url.startsWith( 'Module' )){
							return this.zhuXueServer + '/' + url
						}else{
							return url;
						}
					}
				}
			}
		},
		onLoad(options){
			this.roleName = options.roleName;
			this.realName = options.realName;
			this.mainImg = uni.getStorageSync('userPortrait');
			if(this.roleName == '学生'){
				this.gradeNo = uni.getStorageSync('gradeNo');
			}
			// #ifdef APP-PLUS
			this.formatSize();
			// #endif
		},
		// onShow(){
		// 	// #ifdef APP-PLUS
		// 		this.currVersion = uni.getStorageSync('currVersion');
		// 	// #endif
		// },
		methods:{
			checkVersion(){
				this.config.Update(true,'minePage');
			},
			getbase64Data(data){
				this.mainImg = data;
				uni.showLoading({
					title: '正在上传...',
					icon: 'loading',
					mask: true
				})
				var field = {pathName:'user/head'},that = this;
				var url = '/api/cosFile/cosUpload';
				uni.uploadFile({
					url: url,
					filePath: data,
					header:{
						'token':uni.getStorageSync('token')
					},
					name: 'file', 
					formData:field,
					success:function(res1){
						uni.hideLoading(); 
						if(JSON.parse(res1.data).code == 200){
							var sucSrc = JSON.parse(res1.data).datas.filePath;
							that.upUserHead(sucSrc);
						}else if(JSON.parse(res1.data).code == 1000){
							uni.showToast({
								title : '服务器错误',
								icon : 'none'
							});
						}
					}
				})
			},
			upUserHead(sucSrc){
				var field = {headImg:sucSrc}
				upUserHead(field).then(res=>{
					this.util.showToastSuc('设置成功'); 
					if(!uni.getStorageSync('IMRefuseNum')){//IM未欠费
						//更新即时通讯服务器上的头像
						uni.$TUIKit.updateMyProfile({avatar: sucSrc}).then(res => {}).catch(err=>{});
					}
				}).catch(err=>{});
			},
			goSetSex(){
				var _this = this;
				uni.showActionSheet({
					title:'请选择性别',
					itemList: ['男','女'],
					success: (res)=>{
						if(res.tapIndex == 0){
							this.sexTxt = '男';
						}else if(res.tapIndex == 1){
							this.sexTxt = '女';
						}
						this.upSex();
					},
					fail: function(res) {
						console.log(res.errMsg)
					}
				});
			},
			settingHead(){
				// var that = this;
				// uni.showActionSheet({
				// 	title:'请选择图片',
				// 	itemList: ['从手机相册选择', '拍照'],
				// 	success: (res)=> {
				// 		if(res.tapIndex == 0){
				// 			sourceType = 'album';
				// 		}else if(res.tapIndex == 1){
				// 			sourceType = 'camera';
				// 		}
				// 		this.sculpture(res.tapIndex);
				// 	},
				// 	fail: function(res) {
				// 		console.log(res.errMsg)
				// 	}
				// });
			},
			sculpture(e){
				if (e == 1) {
					//相机
					switch (uni.getSystemInfoSync().platform) {
						case 'android':
							this.requestAndroidPermission('CAMERA',e);
							break;
						case 'ios':
							this.judgeIosPermissionCamera();
							break;
					}
				}else {
					//相册
					switch (uni.getSystemInfoSync().platform) {
						case 'android':
							this.requestAndroidPermission('READ_EXTERNAL_STORAGE',e);
							break;
						case 'ios':
							this.judgeIosPermissionPhotoLibrary();
							break;
					}
				}
			},
			// 安卓相机/相册
			async requestAndroidPermission(permissionID,e) {
				let result = await this.$store.dispatch("permission/requestPermissions",permissionID)
				if (result !== 1) return
				this.upLoadSingleImg(sourceType);
			},
			upLoadSingleImg(sourceType){
				uni.chooseImage({
					count:1,
					sizeType: ['original'], 
					sourceType: [sourceType],// 可以指定来源是相册还是相机，默认二者都有
					success: (res)=>{
						var tempFilePaths = res.tempFilePaths;
						uni.navigateTo({
							url:'../headImgSet/headImgSet?imgSrc=' + tempFilePaths + '&fromPage=settingPage'
						})
					}
				})
			},
			formatSize() {  
				var that = this;  
				plus.cache.calculate(function(size) {  
					let sizeCache = parseInt(size);
					that.sizeCache = sizeCache;
					if (sizeCache == 0) {  
						that.fileSizeString = "0B";  
					} else if (sizeCache < 1024) {  
						that.fileSizeString = sizeCache + "B";  
					} else if (sizeCache < 1048576) {
						that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";  
					} else if (sizeCache < 1073741824) { 
						that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";  
					} else {  
						that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";  
					}
				});  
			},
			clearCache() {
				if(this.sizeCache > 0){
					this.currOpt = 'clearCache';
					this.showAlertFlag = true;
				}else{
					this.util.showToast('暂无缓存');
				}
			},
			sureClear(){
				let that = this;
				let os = plus.os.name;
				uni.showLoading({
					title:'清理中...',
					mask:true
				})
				if (os == 'Android') {
					let main = plus.android.runtimeMainActivity();  
					let sdRoot = main.getCacheDir();  
					let files = plus.android.invoke(sdRoot, "listFiles");  
					let len = files.length;  
					for (let i = 0; i < len; i++) {
						let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {  
							if (entry.isDirectory) {  
								entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录 
									that.showAlertFlag = false;
									uni.showToast({  
										title: '缓存清理完成',  
										duration: 2000  
									});  
									that.formatSize(); // 重新计算缓存
								}, function(e) {  
									console.log(e.message)  
								});  
							} else {  
								entry.remove();  
							}  
						}, function(e) {  
							console.log('文件路径读取失败')  
						});  
					}  
				} else { // ios  
					plus.cache.clear(function() {
						that.showAlertFlag = false;
						uni.showToast({  
							title: '缓存清理完成',  
							duration: 2000  
						});  
						that.formatSize();  
					});  
				}
			},
			sureLogout(){
				this.util.showToastSuc('退出成功');
				this.User.clearStorage();
				this.showAlertFlag = false;
				let pages = getCurrentPages();
				let prevPage = pages[pages.length-2];
				prevPage.$vm.isLoginNum = 0;
				prevPage.$vm.loading = true;
				setTimeout(()=>{
					uni.navigateBack({
						delta:1
					})
				},1500);
			},
			closeAlertComponent(){
				this.showAlertFlag = false;
			},
			cancel(){
				this.showAlertFlag = false;
			},
			logoOut(){
				this.currOpt = 'logOut';
				this.showAlertFlag = true;
			},
		}
	}
</script>
<style lang="scss">
	page{
		background: $pss-bg-primary;
	}
</style>
<style lang='scss' scoped>
	@import '@/static/css/common/alert.scss';
	@import '@/static/scss/helpCen.scss';
	.comBtn{
		width: 600rpx;
		border-radius: 50rpx;
		margin: 100rpx auto 0;
		background: #fff;
		color: $pss-text-color8;
		@include respTo(phone){
			font-size: $font-size30;
		}
		@include respTo(pad){
			height: 70rpx;
			line-height: 70rpx;
			font-size: $padSize20;
		}
	}
	.samePar{
		margin-right: 10rpx;
		margin-top: 10rpx;
		border-radius: 50%;
		@include respTo(phone){
			width: 80rpx;
			height: 80rpx;
		}
		@include respTo(pad){
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>